import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import tkinter as tk
from tkinter import messagebox

# 全局变量
points = []

# 添加点
def add_point():
    try:
        x = float(entry_x.get())
        y = float(entry_y.get())
        z = float(entry_z.get())
        w = float(entry_w.get())
        points.append([x, y, z, w])
        listbox.insert(tk.END, f"({x}, {y}, {z}, {w})")
    except ValueError:
        messagebox.showerror("错误", "请输入有效的数字")

# 删除点
def delete_point():
    try:
        selected = listbox.curselection()
        if not selected:
            messagebox.showerror("错误", "请选择一个点")
            return
        index = selected[0]
        listbox.delete(index)
        points.pop(index)
    except IndexError:
        messagebox.showerror("错误", "没有点可删除")

# 聚类并显示3D散点图
def cluster_and_plot():
    if not points:
        messagebox.showerror("错误", "没有点可聚类")
        return

    # 将四维数据降到三维
    pca = PCA(n_components=3)
    points_3d = pca.fit_transform(points)

    # 聚类
    kmeans = KMeans(n_clusters=3)
    labels = kmeans.fit_predict(points_3d)

    # 绘制3D散点图
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    scatter = ax.scatter(points_3d[:, 0], points_3d[:, 1], points_3d[:, 2], c=labels, cmap='viridis')
    plt.colorbar(scatter)
    plt.show()

# 创建主窗口
root = tk.Tk()
root.title("四维数据降维和聚类")

# 创建文本框和标签
label_x = tk.Label(root, text="X:")
label_x.grid(row=0, column=0)
entry_x = tk.Entry(root)
entry_x.grid(row=0, column=1)

label_y = tk.Label(root, text="Y:")
label_y.grid(row=1, column=0)
entry_y = tk.Entry(root)
entry_y.grid(row=1, column=1)

label_z = tk.Label(root, text="Z:")
label_z.grid(row=2, column=0)
entry_z = tk.Entry(root)
entry_z.grid(row=2, column=1)

label_w = tk.Label(root, text="W:")
label_w.grid(row=3, column=0)
entry_w = tk.Entry(root)
entry_w.grid(row=3, column=1)
# 添加按钮和列表框
button_add = tk.Button(root, text="添加点", command=add_point)
button_add.grid(row=4, column=0, columnspan=2)

button_delete = tk.Button(root, text="删除点", command=delete_point)
button_delete.grid(row=5, column=0, columnspan=2)

button_cluster = tk.Button(root, text="聚类并显示3D散点图", command=cluster_and_plot)
button_cluster.grid(row=6, column=0, columnspan=2)

listbox = tk.Listbox(root)
listbox.grid(row=7, column=0, columnspan=2)

# 运行主循环
root.mainloop()